package com.zyq.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zyq.annotation.Log;
import com.zyq.annotation.PreAuthorize;
import com.zyq.constant.Constant;
import com.zyq.entity.SysUser;
import com.zyq.enuns.DeletedEnum;
import com.zyq.enuns.ResponseCode;
import com.zyq.service.IUserService;
import com.zyq.util.PageResult;
import com.zyq.util.R;
import com.zyq.vo.req.UserAddReqVo;
import com.zyq.vo.req.UserOwnRoleReqVo;
import com.zyq.vo.req.UserPageReqVo;
import com.zyq.vo.req.UserUpdateDetailInfoReqVo;
import com.zyq.vo.req.UserUpdatePasswordReqVo;
import com.zyq.vo.req.UserUpdateReqVo;
import com.zyq.vo.resp.UserOwnRoleRespVo;
import com.zyq.vo.resp.UserRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 用户登陆/登出相关的接口
 */
@RestController
@RequestMapping("/users")
public class UserController extends BaseController{

    // 验证码key
    public static final String CAPTCHA_CODE = "CAPTCHA_CODE";

    @Autowired
    private IUserService userService;

    /**
     * 获取验证码
     * @param request
     * @return
     */
    /*@GetMapping("/captcha")
    public R<Map<String, String>> getCaptchaCode(HttpServletRequest request){
        Map<String,String> map = Maps.newHashMap();
        String code = RandomStringUtils.randomAlphabetic(4);
        request.getSession().setAttribute(CAPTCHA_CODE,code);
        map.put("code",code);
        return R.ok(map);
    }*/

    /**
     * 分页查询用户
     * @param reqVo
     * @return
     */
    @Log(module = "组织管理-用户管理",action = "分页查询用户接口")
    @PreAuthorize(authorize = "sys:user:list")
    @PostMapping("/page")
    public R<PageResult<SysUser>> pageInfo(@RequestBody @Valid UserPageReqVo reqVo){
        QueryWrapper<SysUser> query = Wrappers.query();
        query.lambda().eq(SysUser::getDeleted, DeletedEnum.UNDELETED.getCode());
        PageInfo<SysUser> pageInfo = PageHelper.startPage(reqVo.getPageNum(), reqVo.getPageSize()).doSelectPageInfo(() -> userService.list(query));
        return R.ok(new PageResult<>(pageInfo));
    }

    /**
     * 新增用户
     * @param userAddReqVo
     * @return
     */
    @PreAuthorize(authorize = "sys:user:add")
    @Log(module = "组织管理-用户管理",action = "新增用户接口")
    @PostMapping("/create")
    public R<String> createUser(@RequestBody @Valid UserAddReqVo userAddReqVo){
        return userService.createUser(userAddReqVo);
    }

    /**
     * 查询用户拥有的角色数据接口
     * @param userId
     * @return
     */
    @Log(module = "组织管理-用户管理",action = "查询用户拥有的角色数据接口")
    @GetMapping("/roles/{userId}")
    public R<UserOwnRoleRespVo> getUserOwnRole(@PathVariable("userId")String userId){
        return userService.getUserOwnRole(userId);
    }

    /**
     * 更新用户角色
     * @param vo
     * @return
     */
    @PreAuthorize(authorize = "sys:user:role:update")
    @Log(module = "组织管理-用户管理",action = "保存用户拥有的角色信息接口")
    @PostMapping("/roles")
    public R<String> saveUserOwnRole(@RequestBody @Valid UserOwnRoleReqVo vo){
        return userService.setUserOwnRole(vo);
    }

    /**
     * 重新用户密码
     * @param userId
     * @return
     */
    @PreAuthorize(authorize = "sys:user:role:update")
    @Log(module = "组织管理-重置用户密码",action = "重置用户密码接口")
    @GetMapping("/password/{id}")
    public R<String> resetUpdatePassword(@PathVariable("id") String userId){
        return userService.resetUpdatePassword(userId);
    }

    /**
     * 更新用户
     * @param userUpdateReqVo
     * @param request
     * @return
     */
    @PreAuthorize(authorize = "sys:user:update")
    @Log(module = "组织管理-用户管理",action = "列表修改用户信息接口")
    @PostMapping("/update")
    public R<String> updateUserInfo(@RequestBody @Valid UserUpdateReqVo userUpdateReqVo, HttpServletRequest request){
        String accessToken = request.getHeader(Constant.User.ACCESS_TOKEN);
        String userId = getUserId(accessToken);// 操作人
        if (userId == null){
            return R.error(ResponseCode.TOKEN_NO_AVAIL.getMessage());
        }
        return userService.updateUserInfo(userUpdateReqVo,userId);
    }

    /**
     * 批量/删除用户接口
     * @param list @ApiParam(value = "用户id集合")
     * @param request
     * @return
     */
    @PreAuthorize(authorize = "sys:user:delete")
    @Log(module = "组织管理-用户管理",action = "批量/删除用户接口")
    @PostMapping("/delete")
    public R<String> deletedUsers(@RequestBody List<String> list, HttpServletRequest request){
        String accessToken = request.getHeader(Constant.User.ACCESS_TOKEN);
        String userId = getUserId(accessToken);// 操作人
        if (userId == null){
            return R.error(ResponseCode.TOKEN_NO_AVAIL.getMessage());
        }
        return userService.deletedUsers(list,userId);
    }

    /**
     * 用户信息详情
     * @param request
     * @return
     */
    @Log(module = "组织管理-用户管理",action = "用户信息详情接口")
    @GetMapping("/info")
    public R<UserRespVo> detailInfo(HttpServletRequest request){
        String accessToken = request.getHeader(Constant.User.ACCESS_TOKEN);
        String userId = getUserId(accessToken);// 操作人
        if (userId == null){
            return R.error(ResponseCode.TOKEN_NO_AVAIL.getMessage());
        }
        return userService.detailInfo(userId);
    }

    /**
     * 保存个人信息
     * @param updateDetailInfoReqVo
     * @param request
     * @return
     */
    @Log(module = "组织管理-用户管理",action = "保存个人信息接口")
    @PutMapping("/user/info")
    public R<String> saveUserInfo(@RequestBody UserUpdateDetailInfoReqVo updateDetailInfoReqVo, HttpServletRequest request){
        String accessToken = request.getHeader(Constant.User.ACCESS_TOKEN);
        String userId = getUserId(accessToken);// 操作人
        if (userId == null){
            return R.error(ResponseCode.TOKEN_NO_AVAIL.getMessage());
        }
        return userService.userUpdateDetailInfo(updateDetailInfoReqVo,userId);
    }

    /**
     * 修改个人密码
     * @param userUpdatePasswordReqVo
     * @param request
     * @return
     */
    @Log(module = "组织管理-用户管理",action = "修改个人密码接口")
    @PutMapping("/user/password")
    public R<String> updatePassword(@RequestBody @Valid UserUpdatePasswordReqVo userUpdatePasswordReqVo, HttpServletRequest request){
        String accessToken = request.getHeader(Constant.User.ACCESS_TOKEN);
        //String refreshToken = request.getHeader(Constant.REFRESH_TOKEN);
        String userId = getUserId(accessToken);// 操作人
        if (userId == null){
            return R.error(ResponseCode.TOKEN_NO_AVAIL.getMessage());
        }
        return userService.userUpdatePassword(userUpdatePasswordReqVo,userId);
    }
}
